import React, { useState, useEffect } from 'react'
import { View, Text, Picker } from '@tarojs/components'
import Taro from '@tarojs/taro'
import PageWrapper from '@/components/PageWrapper'
import MultiImageUploader from "@/components/MultiImageUploader/MultiImageUploader"
import { useDictData, DictItem } from '@/hook/useDictData'
import { request } from '@/utils/request'
import './index.scss'

const AppraiserAuthPage = () => {
  const [images, setImages] = useState<string[]>([])
  const { data: typeListData, loading } = useDictData('appraisal_category')
  const [selectedIndex, setSelectedIndex] = useState(0)

  const handleChange = (e) => {
    setSelectedIndex(e.detail.value)
  }

  const handleSubmit = async () => {
    if (!images.length) {
      Taro.showToast({ title: '请上传证书图片', icon: 'none' })
      return
    }

    const selectedValue = typeListData[selectedIndex]?.value
    if (!selectedValue) {
      Taro.showToast({ title: '请选择鉴定品类', icon: 'none' })
      return
    }

    try {
      await request.post('/member/appraiser-auth/create', {
        certificateUrls: images,
        type: selectedValue
      })
      Taro.showToast({ title: '提交成功', icon: 'success' })
    } catch (err) {
      console.error(err)
      Taro.showToast({ title: '提交失败', icon: 'none' })
    }
  }

  return (
    <PageWrapper title="鉴定师认证" showBack={true} backgroundColor="#F0F0F0">
      <View className="my-service-page">
        <View className="title-item-box">
          <View className="title-item">鉴定品类</View>

          <View className="selector-container">
            <Text className="label">类型：</Text>
            {!loading && typeListData.length > 0 && (
              <Picker mode="selector" range={typeListData.map(item => item.label)} onChange={handleChange}>
                <View className="picker-view">
                  {typeListData[selectedIndex]?.label || '请选择'}
                </View>
              </Picker>
            )}
          </View>

          <View className="sell-viedo-up">
            <MultiImageUploader
              maxCount={2}
              value={images}
              onChange={(newList) => setImages(newList)}
            />
          </View>
        </View>

        <View className="submit-but orange-bg" onClick={handleSubmit}>
          鉴定师认证
        </View>
      </View>
    </PageWrapper>
  )
}

export default AppraiserAuthPage
